package main;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;


public class HTTPServer {
	public static void main(String args[]) {

		int port;
		String name;
		FileUtil fileUtil = new FileUtil();

		ServerSocket server_socket;
		try {
			name = args[0];
			port = Integer.parseInt(args[1]);
		} catch (Exception e) {
			name = "User1";
			port = 1500;
		}

		UserInputListener listener = new UserInputListener(name, port, fileUtil);
		Thread listenerThread = new Thread(listener);
		listenerThread.start();
		try {

			server_socket = new ServerSocket(port);
			System.out.println("httpServer running on port "
					+ server_socket.getLocalPort());

			// server infinite loop
			while (true) {
				Socket socket = server_socket.accept();
				// System.out.println("New connection accepted "
				// + socket.getInetAddress() + ":" + socket.getPort());

				// Construct handler to process the HTTP request message.
				try {
					HTTPRequestHandler request = new HTTPRequestHandler(socket,
							fileUtil, listener, listenerThread);
					// Create a new thread to process the request.
					Thread thread = new Thread(request);

					// Start the thread.
					thread.start();
				} catch (Exception e) {
					System.out.println(e);
				}
			}
		} catch (IOException e) {
			System.out.println(e);
		}
	}
}
